package com.xxs.model;

import java.util.Date;
import java.util.List;

import com.jfinal.kit.HashKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.xxs.common.Const;
import com.xxs.model.base.BaseAdmin;

/**
 */
@SuppressWarnings("serial")
public class Admin extends BaseAdmin<Admin>  {

    public static final Admin dao = new Admin();
    private static final String ADMIN_CACHE = "admin";
    private static final String ADMIN_LIST_CACHE = "adminList";
    
    public Admin getByEmailAndPassword(String email, String password){
    	password = HashKit.md5(password);
        return dao.findFirst("select id, adminname, email, password from xm_admin where email=? and password=?", email, password);
    }
    
    public List<Admin> getAdminListbyPoint(int count){
        return dao.findByCache(ADMIN_LIST_CACHE, 1, "select * from xm_admin order by point desc limit 0,?",count);
    }
    
    public void mySave(){
        String password = HashKit.md5(this.getStr("password"));
        this.set("password", password).set("registDate", new Date());
        // bug,数据库默认头像没生效
        this.removeNullValueAttrs();
        this.save();
    }

    public void myUpdate() {
        this.update();
        removeThisCache(this.getInt("id"));
    }
    public boolean containEmail(String email) {
        return dao.findFirst("select email from xm_admin where email=? limit 1", email) != null;
    }
    public boolean containAdminname(String adminname) {
        return dao.findFirst("select adminname from xm_admin where adminname=? limit 1", adminname) != null;
    }
    public boolean containEmailExceptThis(int adminID, String email) {
        return dao.findFirst("select email from xm_admin where email=? and id!=? limit 1", email, adminID) != null;
    }
    public boolean containAdminnameExceptThis(int adminID, String adminname) {
        return dao.findFirst("select adminname from xm_admin where adminname=? and id!=? limit 1", adminname, adminID) != null;
    }

    /* getter */
    public boolean getIsAdmin(String email) {
        return Const.ADMIN_EMAIL.equals(email);
    }

    /* cache */
    private void removeThisCache(int id){
        CacheKit.remove(ADMIN_CACHE, id);
    }
}
